import { Generator } from "./../engine/generator";
import * as THREE from "three";
import { CameraControl } from "../control/cameraControl";
import { KeyboardControl } from "../control/keyboardControl";
import { sceneOption as _opts } from "../state/index";
import { Mask } from "../view/mask";
import { mloader } from "../loader/objLoader";
import { Group } from "three";

export class SceneManager {
  constructor() {
    this.initDom();
    this.initScene();
    this.initGenerator();
    this.initControl();
    this.initModel();
  }

  /**
   * 初始化DOM
   */
  public initDom(): void {
    // canvas包含器
    let dom = document.createElement("div");
    dom.style.height = "100%";
    dom.style.width = "100%";
    _opts.dom = dom;
    document.body.append(_opts.dom);

    // 蒙版包含器
    let mask = new Mask();
  }

  /**
   * 初始化构建场景
   */
  public initGenerator(): void {
    let generator = new Generator();
    generator.generateGround();
    generator.generateBarrier(50);
  }

  /**
   * 加载scene
   */
  public initScene(): void {
    _opts.scene = new THREE.Scene();
    _opts.clock = new THREE.Clock();
    _opts.camera = new THREE.PerspectiveCamera(
      45,
      window.innerWidth / window.innerHeight,
      0.1,
      1000
    );
    _opts.renderer = new THREE.WebGLRenderer();
    _opts.renderer.setClearColor(new THREE.Color(0xeeeeee));
    _opts.renderer.setSize(window.innerWidth, window.innerHeight);

    const mesh = new THREE.Mesh(
      new THREE.BoxGeometry(1, 1, 1),
      new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true })
    );
    _opts.scene.add(mesh);

    // 添加格网与坐标轴
    const gridHelper = new THREE.GridHelper(50, 50, "#3d3d3d", "#a3a3a3");
    gridHelper.position.y = -1;
    gridHelper.name = "gridHelper";
    _opts.scene.add(gridHelper);
    // 添加坐标轴
    const axesHelper = new THREE.AxesHelper(50);
    _opts.scene.add(axesHelper);
    // add subtle ambient lighting
    var ambientLight = new THREE.AmbientLight("#696969");
    _opts.scene.add(ambientLight);

    // add spotlight for the shadows
    var spotLight = new THREE.SpotLight(0xffffff);
    spotLight.position.set(-40, 60, -10);
    spotLight.castShadow = true;
    _opts.scene.add(spotLight);

    _opts.camera.position.set(0, 0, 5);
    _opts.camera.lookAt(_opts.scene.position);
    _opts.dom.appendChild(_opts.renderer.domElement);
    _opts.renderer.render(_opts.scene, _opts.camera);
  }

  /**
   * 初始化控件
   */
  public initControl(): void {
    let cControl = new CameraControl();
    _opts.cameraControl = cControl.instance;

    // let kControl = new KeyboardControl();
  }

  public initModel(): void{
    let data = require("../model/pistol.obj").default;
    let model = new mloader(data, res => {
      let group: Group = res;
      let kControl = new KeyboardControl(group);
      group.scale.set(.1, .1, .1);
      group.rotateX(-Math.PI / 2);
      group.position.set(0, 0 ,0);
      _opts.scene.add(group);
    });
  }
}
